C# Iteration Constructs

All programming languages provide ways to repeat blocks of code until a terminating condition has been met. Regardless of which language you have used in the past, the C# iteration statements should not raise too many eyebrows and should require little explanation. C# provides the following four iteration constructs:

Let's quickly examine each looping construct in turn, using a new Console Application project named IterationsAndDecisions.

The for Loop

When you need to iterate over a block of code a fixed number of times, the for statement provides a good deal of flexibility. In essence, you are able to specify how many times a block of code repeats itself, as well as the terminating condition. Without belaboring the point, here is a sample of the syntax.

// A basic for loop.
static void ForAndForEachLoop()
{
    // Note! "i" is only visible within the scope of the for loop.
    for(int i = 0; i < 4; i++)
    {
        Console.WriteLine("Number is: {0} ", i);
    }
    // "i" is not visible here.
}

All of your old C, C++, and Java tricks still hold when building a C# for statement. You can create complex terminating conditions, build endless loops, and make use of the goto, continue, and break keywords. I'll assume that you will bend this iteration construct as you see fit. Consult the .NET Framework 4.0 SDK documentation if you require further details on the C# for keyword.

The foreach Loop

The C# foreach keyword allows you to iterate over all items within an array (or a collection object; see Chapter 10) without the need to test for an upper limit. Here are two examples using foreach-one to traverse an array of strings and the other to traverse an array of integers.

// Iterate array items using foreach.
static void ForAndForEachLoop()
{
...
    string[] carTypes = {"Ford", "BMW", "Yugo", "Honda" };
    foreach (string c in carTypes)
        Console.WriteLine(c);
    
    int[] myInts = { 10, 20, 30, 40 };
    foreach (int i in myInts)
        Console.WriteLine(i);
}

In addition to iterating over simple arrays, foreach is also able to iterate over system-supplied or user-defined collections. I'll hold off on the details until Chapter 9, as this aspect of the foreach keyword entails an understanding of interface-based programming and the role of the IEnumerator and IEnumerable interfaces.

Use of var Within foreach Constructs

It is also possible to make use of implicit typing within a foreach looping construct. As you would expect, the compiler will correctly infer the correct "type of type." Consider the following method, which iterates over a local array of integers:

static void VarInForeachLoop()
{
    int[] myInts = { 10, 20, 30, 40 };
    
    // Use "var" in a standard foreach loop.
    foreach (var item in myInts)
    {
        Console.WriteLine("Item value: {0}", item);
    }
}

Understand that in this example there is no compelling reason to use the var keyword in our foreach loop, as we can clearly see that we are indeed iterating over an array of integers. But once again, when using the LINQ programming model, using var within a foreach loop will be very useful, and in some cases, absolutely mandatory.

The while and do/while Looping Constructs

The while looping construct is useful should you wish to execute a block of statements until some terminating condition has been reached. Within the scope of a while loop, you will need to ensure this terminating event is indeed established; otherwise, you will be stuck in an endless loop. In the following example, the message "In while loop" will be continuously printed until the user terminates the loop by entering yes at the command prompt:

static void ExecuteWhileLoop()
{
    string userIsDone = "";

    // Test on a lower-class copy of the string.
    while(userIsDone.ToLower() != "yes")
    {
        Console.Write("Are you done? [yes] [no]: ");
        userIsDone = Console.ReadLine();
        Console.WriteLine("In while loop");
    }
}

Closely related to the while loop is the do/while statement. Like a simple while loop, do/while is used when you need to perform some action an undetermined number of times. The difference is that do/while loops are guaranteed to execute the corresponding block of code at least once. In contrast, it is possible that a simple while loop may never execute if the terminating condition is false from the onset.

static void ExecuteDoWhileLoop()
{
    string userIsDone = "";
    do
    {
        Console.WriteLine("In do/while loop");
        Console.Write("Are you done? [yes] [no]: ");
        userIsDone = Console.ReadLine();
    }while(userIsDone.ToLower() != "yes"); // Note the semicolon!
}